package tio.study.showcase.client;

import org.tio.client.ClientChannelContext;
import org.tio.client.ReconnConf;
import org.tio.client.TioClient;
import org.tio.client.TioClientConfig;
import org.tio.client.intf.TioClientHandler;
import org.tio.client.intf.TioClientListener;
import org.tio.core.Node;
import org.tio.core.Tio;
import org.tio.utils.json.Json;
import tio.study.showcase.common.Const;
import tio.study.showcase.common.ShowcasePacket;
import tio.study.showcase.common.Type;
import tio.study.showcase.common.packets.LoginReqBody;

/**
 * @description:
 * @author: zhou shuai
 * @date: 2022/12/1 20:14
 * @version: v1
 */
public class LoginClientStarter {

    static String serverIp = "127.0.0.1";
    static int serverPort = Const.PORT;

    private static Node serverNode = new Node(serverIp, serverPort);
    /**
     * 用来自动连接的，不想自动连接请设为null
     */
    private static ReconnConf reconnConf = new ReconnConf(5000L);

    private static TioClientHandler tioClientHandler = new ShowcaseClientTioHandler();

    private static TioClientListener tioClientListener = new ShowcaseClientTioListener();
    /**
     * 一组连接共用的上下文对象
     */
    public static TioClientConfig tioClientConfig = new TioClientConfig(tioClientHandler, tioClientListener, reconnConf);

    private static TioClient tioClient = null;

    static ClientChannelContext clientChannelContext;

    public static void main(String[] args) throws Exception {
        tioClient = new TioClient(tioClientConfig);
        clientChannelContext = tioClient.connect(serverNode);
        command();
    }

    public static void command() throws Exception {
        String loginname = "hwy";
        String password = "123456";
        while (true){
            processCommand(loginname, password);
            Thread.sleep(2000);
        }

        //tioClient.stop();
        //System.exit(0);
    }

    public static void processCommand(String loginname, String password) throws Exception {

        LoginReqBody loginReqBody = new LoginReqBody();
        loginReqBody.setLoginname(loginname);
        loginReqBody.setPassword(password);

        ShowcasePacket reqPacket = new ShowcasePacket();
        reqPacket.setType(Type.LOGIN_REQ);
        reqPacket.setBody(Json.toJson(loginReqBody).getBytes(ShowcasePacket.CHARSET));

        Tio.send(clientChannelContext, reqPacket);
    }

}
